import axios from 'axios';



const service = axios.create({
    baseURL: getBaseUrl(),
    timeout: 60000,
    // headers: {}
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
    }
})

// 对token加密
function getToken() {
    const tokenObj = JSON.parse(sessionStorage.getItem('kcisxa-healthcenter-token'));
    if(tokenObj && tokenObj.token) {
        return tokenObj.token
    }
    return ''
}

/**
 * <p>请求拦截器设置token
 */
service.interceptors.request.use(function (config) {
    if(!config.headers) {
        if (config.method === 'post' || config.method === "POST") {
            //config.headers['Content-Type'] = 'text/plain;charset=UTF-8'
            config.headers['Content-Type'] = 'application/json;charset=UTF-8'
        }
    }
    const token = getToken()
    if(token) {
        config.headers['Authorization'] = token
    }
    return config
}, function (error) {
    return Promise.reject(error);
});


/**
 * <p>响应拦截器,处理全局信息
 */
service.interceptors.response.use(function (response) {
    const { status, statusText, data } = response;
    if (status === 200) {
        //此处判断是否下载请求
        if (response.headers['content-type'] === 'application/octet-stream') {
            //根据响应头获取文件名称
            let fileName = response.headers['content-disposition'].match(/filename=(.*)/)[1]
            if (fileName) {
                fileName = decodeURI(fileName)
            } else {
                //此处表示后台没有设置响应头 content-disposition,请根据业务场景自行处理
                fileName = "download.txt"
            }
            const blob = new Blob([response.data], { type: 'application/octet-stream' })
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                window.navigator.msSaveBlob(blob, fileName)
            } else {
                const blobURL = window.URL.createObjectURL(blob)
                const tempLink = document.createElement('a')
                tempLink.style.display = 'none'
                tempLink.href = blobURL
                tempLink.setAttribute('download', fileName)
                if (typeof tempLink.download === 'undefined') {
                    tempLink.setAttribute('target', '_blank')
                }
                document.body.appendChild(tempLink)
                tempLink.click()
                document.body.removeChild(tempLink)
                window.URL.revokeObjectURL(blobURL)
            }
        } else {
        	//非下载请求返回的数据为json
            return response.data
        }
    } else {
        console.error(status, statusText, data)
    }
    return response;
}, function (error) {
    // console.error(error)
    return Promise.reject(error);
});


export default service;


/**
 * <p>根据激活的环境获取回款系统的接口地址
 * @returns {*}
 */
export function getBaseUrl() {
    return "/healthcenter/api";
}

